<!-- 排座表格 -->
<template>
  <div>
    <div v-for="(group, groupIndex) in currentData" :key="groupIndex" style="border: solid 1px #e5e5e5;" class="_mt-10">
      <div class="disFlxJS rowTitle _pl-10 _pr-10 fw-6">
        <div>
          <span class="_mr-8">
            <span>序号：</span>
            <span>{{ group.serialNumber }}</span>
          </span>
          <a-button type="primary" ghost @click="openModifyGroupSortModel(group.serialNumber)">
            修改组排序
          </a-button>
        </div>
        <div v-if="group.operability" class="disFlxAC">
          <a-input
            v-model="group.name"
            @blur="editGroupName(group)"
            :id="'groupNameInput' + group.id"
            style="text-align: center;width:100px;"
          />
        </div>
        <div v-else class="disFlxAC">
          <div>{{ group.name }}</div>
          <div class="_pl-5 _pr-5 cup" @click="_toggle(group)">
            <a-icon type="edit" />
          </div>
        </div>

        <div>已分配 {{ getGroupLockSeatNum(group.seatVoList) }}/{{ group.seatVoList.length }}</div>
      </div>
      <div class="disFlxJS _pl-10 _pr-10 _pt-5 _pb-5">
        <div class="disFlxAC">
          <a-tag :color="getGroupLockSeatNum(group.seatVoList) === group.seatVoList.length ? 'red' : 'orange'">
            {{ getGroupLockSeatNum(group.seatVoList) === group.seatVoList.length ? '已排满' : '未排满' }}
          </a-tag>
          <span class="color9 fz-12">排座表格可拖动行进行排序或交换位置</span>
        </div>
        <div class="disFlxAC">
          <a-tag color="#f50" class="cup" @click.stop="removeGroup(group)">
            删除组
          </a-tag>
          <a-tag color="#87d068" class="cup" @click.stop="openSelectUserModel(1, group.id)">
            批量选择人员
          </a-tag>
          <a-tag v-if="locationRule === 'IMPORT'" color="blue" class="cup" @click="openImportCodeModel(group.id)">
            导入位置编号
          </a-tag>
        </div>
      </div>
      <!-- <GroupTable
        v-bind="$attrs"
        v-on="$listeners"
        :ref="`groupTable${group.id}`"
        :tableId="group.id"
        :locationRule="locationRule"
        :tableData="group.seatVoList"
        @openSelectUserModel="openSelectUserModel"
        @openChangePlaceModel="$event => openChangePlaceModel($event, group)"
      /> -->
      <VirtualGroupTable 
        v-bind="$attrs"
        v-on="$listeners"
        :ref="`groupTable${group.id}`"
        :tableId="group.id"
        :locationRule="locationRule"
        :tableData="group.seatVoList"
        @openSelectUserModel="openSelectUserModel"
        @openChangePlaceModel="$event => openChangePlaceModel($event, group)"/>
    </div>
    <div class="_pt-10 textRight">
      <!-- :hideOnSinglePage="true"  -->
      <a-pagination
        :item-render="_paginationRender"
        show-quick-jumper
        v-model="currentPage"
        :total="groupList.length"
        showSizeChanger
        :pageSize.sync="currentSize"
        :pageSizeOptions="['10']"
        @change="_paginationChange"
        @showSizeChange="_paginationChange"
      />
    </div>

    <ModifyGroupSortModel ref="modifyGroupSortModel" @submit="modifyGroupSortModelSubmit" />
    <ChangePlaceModel
      v-if="activityArrangeId"
      ref="changePlaceModel"
      :activityArrangeId="activityArrangeId"
      @submit="changePlaceModelSubmit"
    />

    <SelectUserModel
      ref="SelectUserModel"
      :activityId="activityId"
      :activityArrangeId="activityArrangeId"
      @submit="selectUserSubmit"
    />
    <ImportCodeModel ref="ImportCodeModel" @submit="importCodeSubmit" />
  </div>
</template>

<script>
import SelectUserModel from './selectUserModel'
import ImportCodeModel from './importCodeModel'
import GroupTable from './groupTable'
import {
  editActivityArrangeGroup,
  delActivityArrangeGroup,
  activityArrangeBatchAssignedSeat,
  activityArrangeAssignedSeat,
  activityArrangeAssignedSeatToLockSeat,
  activityArrangeImportSeatCode
} from '@/api/activity/activity.js'
import { cloneDeep } from 'lodash-es'
import ModifyGroupSortModel from './modifyGroupSortModel.vue'
import ChangePlaceModel from './changePlaceModel.vue'
import VirtualGroupTable from './virtualGroupTable.vue'

export default {
  inheritAttrs: false,
  props: {
    // 活动ID
    activityId: {
      type: Number | String
    },
    // 场次ID
    activityArrangeId: {
      type: Number | String
    },
    // 当前场次的组列表
    groupList: {
      type: Array,
      required: true,
      default: () => []
    },
    // 位置排座方式 AUTO 自动生成 IMPORT 导入
    locationRule: {
      type: String,
      default: 'AUTO'
    }
  },
  watch: {
    activityArrangeId() {
      this._refresh(true)
    },
    groupList: {
      handler() {
        this._refresh()
      },
      deep: true
    }
  },
  components: {
    SelectUserModel,
    ImportCodeModel,
    GroupTable,
    ModifyGroupSortModel,
    ChangePlaceModel,
    VirtualGroupTable
  },
  data() {
    return {
      operability: false, // 组名称是否可操作
      oldGroupName: '', // 初始组名
      currentPage: 1, // 当前页数
      currentSize: 10, // 当前条数
      currentData: [] // 当前显示组
    }
  },
  methods: {
    /** 打开交换位置弹窗 */
    openChangePlaceModel(rowData) {
      this.$refs.changePlaceModel.openModel(rowData)
    },
    // 打开修改排序弹窗
    openModifyGroupSortModel(index) {
      this.$refs.modifyGroupSortModel.openModel(index)
    },
    modifyGroupSortModelSubmit(form) {
      this.$emit('modifyGroupSort', form)
      // this.currentPage = Math.ceil(form.newSort / this.currentSize)
      // this._refresh()
    },
    changePlaceModelSubmit(form) {
      this.currentData = []
      this.$emit('changePlaceModel', form)
      this.$refs.changePlaceModel.closeModel()
    },
    // 刷新列表
    _refresh(isReset) {
      if (isReset) {
        this.currentPage = 1
        this.currentSize = 10
      }
      this._paginationChange(this.currentPage, this.currentSize)
    },
    // 分页器增加快捷跳转
    _paginationRender(current, type, originalElement) {
      if (type === 'prev') {
        return <a>上一页</a>
      } else if (type === 'next') {
        return <a>下一页</a>
      }
      return originalElement
    },
    // 分页跳转
    _paginationChange(page, pageSize) {
      this.currentPage = page
      const start = (page - 1) * pageSize
      const end = page * pageSize
      
      const oldCurrentData = cloneDeep(this.currentData)
      const newCurrentData = cloneDeep(this.groupList.slice(start, end))
      this.currentData = newCurrentData.map(v => {
        const findItem = oldCurrentData.find(item => item.id === v.id)
        if (findItem) {
          v.lockSeatNum = findItem.lockSeatNum
          v.maxSeatNum = findItem.maxSeatNum
          v.seatVoList = findItem.seatVoList
        }
        return v
      })
    },
    _toggle(group) {
      this.oldGroupName = group.name
      this.$set(group, 'operability', true)
      this.$nextTick(() => {
        const tbList = this.$el.querySelector(`#groupNameInput${group.id}`)
        tbList.focus() // 输入款自动聚焦
      })
    },
    // 修改组名称-前端静默更新
    editGroupName(group) {
      const _this = this
      group.operability = false
      if (!group.name || group.name === _this.oldGroupName) {
        group.name = _this.oldGroupName
        return
      }
      const { tableData } = _this.$refs[`groupTable${group.id}`][0]
      _this.$refs[`groupTable${group.id}`][0].loading = true
      editActivityArrangeGroup({ id: group.id, name: group.name })
        .then(() => {
          _this.$message.success('修改组名成功')
          tableData.forEach(v => {
            v.displayName = v.displayName.replace(new RegExp(_this.oldGroupName, 'g'), group.name)
            v.groupName = group.name
          })
          _this.$refs[`groupTable${group.id}`][0].loading = false
        })
        .catch(() => {
          _this.$refs[`groupTable${group.id}`][0].loading = false
        })
    },
    // 删除当前组
    removeGroup(group) {
      const _this = this
      _this.$confirm({
        title: `确认删除${group.name}?`,
        centered: true,
        content: '删除该组后,该组下的排座信息将彻底删除,请确定是否删除?',
        onOk() {
          return new Promise((resolve, reject) => {
            _this.$refs[`groupTable${group.id}`][0].loading = true
            delActivityArrangeGroup({ groupId: group.id })
              .then(() => {
                _this.$message.success('删除组成功')
                if (_this.currentData[0].id === group.id) {
                  _this.currentPage = _this.currentPage <= 1 ? 1 : _this.currentPage - 1
                }
                _this.$emit('remove', group.id, _this.currentData) // 删除分组-父组件数据改动，watch监听会自动刷新列表
                _this.$refs[`groupTable${group.id}`][0].loading = false
                _this.$emit('resetHead') // 刷新头部信息
                resolve()
              })
              .catch(() => {
                _this.$refs[`groupTable${group.id}`][0].loading = false
                reject()
              })
          })
        },
        onCancel() {}
      })
    },
    // 打开导入座位弹窗
    openImportCodeModel(groupId) {
      this.$refs.ImportCodeModel.openModel(groupId)
    },
    // 导入座位确认-根据后端返回更新
    importCodeSubmit(form) {
      const _this = this
      const { tableData } = this.$refs[`groupTable${form.groupId}`][0]
      this.$refs[`groupTable${form.groupId}`][0].loading = true
      activityArrangeImportSeatCode(form)
        .then(res => {
          _this.$message.success('导入位置成功')
          if (res.data) {
            tableData.push(...res.data)
            _this.$emit('resetHead') // 刷新头部信息
          }
          const seatList = form.importSeatCodeStr.split(',')
          let lastIndex = 0 // 最后一个位置
          tableData.forEach((v, i) => {
            if (form.rule === 'COVER') {
              // 覆盖导入
              _this.$set(v, 'displayName', seatList[i] || null)
            } else {
              // 追加导入 从最后一个座位之后追加
              if (v.displayName) {
                lastIndex = i + 1
              }
            }
          })
          if (form.rule === 'APPEND') {
            // 追加导入
            tableData.forEach((v, i) => {
              if (i >= lastIndex && seatList.length) {
                _this.$set(v, 'displayName', seatList[0])
                seatList.splice(0, 1)
              }
            })
          }
          console.log(lastIndex, '最后的位置')
          _this.$refs.ImportCodeModel.closeModel()
          _this.$refs[`groupTable${form.groupId}`][0].loading = false
        })
        .catch(() => {
          _this.$refs[`groupTable${form.groupId}`][0].loading = false
        })
    },

    // 选择人员 type 1: 批量选择人员 2.指定座位添加人员 3.指定座位添加人员(座位为占座)
    openSelectUserModel(type, groupId, seatId) {
      this.$refs.SelectUserModel.openModel(type, groupId, seatId)
    },
    // 确认选择人员-根据后端返回更新
    async selectUserSubmit(params) {
      const _this = this
      const { tableData } = _this.$refs[`groupTable${params.groupId}`][0]
      _this.$refs[`groupTable${params.groupId}`][0].loading = true
      try {
        if (params.type === 1) {
          // 批量用户排座
          const { data } = await activityArrangeBatchAssignedSeat(params)
          data.forEach(row => {
            tableData.forEach(v => {
              if (row.id === v.id) {
                v.userId = row.userId
                v.userName = row.userName
                v.userPosition = row.userPosition
                v.userCompanyName = row.userCompanyName
              }
            })
          })
        } else {
          // 2: 指定用户排座 || 3: 指定用户排座(座位为占座座位)
          if (params.type === 2) {
            await activityArrangeAssignedSeat(params)
          } else {
            await activityArrangeAssignedSeatToLockSeat(params)
          }
          tableData.forEach(v => {
            if (v.id === params.seatId) {
              v.userId = params.userId
              v.userName = params.userName
              v.userPosition = params.userPosition
              v.userCompanyName = params.userCompanyName
            }
          })
        }
        _this.$emit('resetHead') // 刷新头部信息
        _this.$message.success('排座成功')
        _this.$refs.SelectUserModel.closeModel()
        _this.$refs[`groupTable${params.groupId}`][0].loading = false
      } catch (error) {
        _this.$refs[`groupTable${params.groupId}`][0].loading = false
      }
    },
    getGroupLockSeatNum(list) {
      let tableLockSeatNum = 0
      list.forEach(v => {
        if (!!v.userId) {
          tableLockSeatNum++
        }
      })
      return tableLockSeatNum || 0
    }
  }
}
</script>

<style lang="less" scoped>
.rowTitle {
  height: 40px;
  line-height: 40px;
  background-color: #bddfff;
}
.textRight {
  text-align: right;
}
</style>
